﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class Popup_FindFriend : Popup_Base
{
	const string FIND_FRIEND_CELL_NAME = "Cell - Find Friend";

	public GameObject emptyListObject;
	public GameObject findFriendCell;
	public UIGrid findFriendGrid;
	public UIScrollView findFriendScrollView;
	public UIInput friendNameInput;
	public GameObject sceneObject;

	string initialFriendNameText;

	Dictionary<int, FriendModel> findFriendList = new Dictionary<int, FriendModel>();
	Dictionary<int, GameObject> findFriendObjectList = new Dictionary<int, GameObject>();

	public override void AwakeInit ()
	{
		initialFriendNameText = friendNameInput.label.text;
	}

	public override void BackButton()
	{
		PopupManager.PopPopup();
	}

	public void FindFriendProcess(int selectedIndexPath)
	{
		if (sceneObject.GetComponent<MessageScene>() != null)
		{
			sceneObject.GetComponent<MessageScene>().receiverId = findFriendList[selectedIndexPath].id;
			sceneObject.GetComponent<MessageScene>().receiverNameLabel.text = findFriendList[selectedIndexPath].name;
		}

		else if (sceneObject.GetComponent<Popup_WriteMessage>() != null)
		{
			sceneObject.GetComponent<Popup_WriteMessage>().receiverId = findFriendList[selectedIndexPath].id;
			sceneObject.GetComponent<Popup_WriteMessage>().receiverNameInput.value = findFriendList[selectedIndexPath].name;
		}

		BackButton();
	}

	void RemoveAllFindFriend()
	{
		findFriendList.Clear();
		
		foreach (KeyValuePair<int, GameObject> pair in findFriendObjectList)
		{
			NGUITools.SetActive(pair.Value, false);
			NGUITools.Destroy(pair.Value);
		}
		findFriendObjectList.Clear();
	}

	public void OnClick_FindFriendButton()
	{
		if (string.Compare(friendNameInput.label.text.Trim(), initialFriendNameText) == 0 || friendNameInput.label.text.Trim().Length <= 0)
		{
			PopupUtility.OneButtonErrorPopupNoBackground(Localization.Get("uiFriendInputName"));
			return;
		}
		
		NetworkManager.Instance.C2S_FRIEND_SEARCH(friendNameInput.label.text, ( responseData ) => {
			
			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopupNoBackground(responseData.ecode);
				NGUITools.SetActive(emptyListObject, true);
				return;
			}
			
			GameObject g = null;
			int idx = 0;
			
			RemoveAllFindFriend();
			
			NGUITools.SetActive(emptyListObject, false);
			
			FriendModel fm = responseData.data;

			// (s) 한개의 결과만 나온지만 우선은 기존의 자료구조에 넣음
			g = NGUITools.AddChild(findFriendGrid.transform.gameObject, findFriendCell);
			g.transform.localScale = Vector3.one;
			g.name = FIND_FRIEND_CELL_NAME;
			
			FindFriendCell ffc = g.GetComponent<FindFriendCell>();
			ffc.indexPath = idx;
			
			ffc.nameLabel.text = fm.name;
			ffc.levelLabel.text = string.Format("Lv {0}", fm.lv.ToString());
			ffc.lastAccessLabel.text = DatetimeToFomattedString(fm.lastAccess);
			
			findFriendObjectList.Add (idx, g);
			findFriendList.Add (idx, fm);
			
			NGUITools.SetActive(g, true);
			// (e) 한개의 결과만 나온지만 우선은 기존의 자료구조에 넣음

			findFriendGrid.Reposition();
			findFriendScrollView.ResetPosition();
		});
	}

	/*
	 * TODO: (친구 검색 목록 결과가 여러개 였을 때의 매소드 : 다시 이것으로 바뀔 수 있어서 남겨둠)
	 * 
	public void OnClick_FindFriendButton()
	{
		if (string.Compare(friendNameInput.label.text.Trim(), initialFriendNameText) == 0 || friendNameInput.label.text.Trim().Length <= 0)
		{
			PopupUtility.OneButtonErrorPopup("No Friend Name");
			return;
		}

		NetworkManager.Instance.C2S_FRIEND_SEARCH(friendNameInput.label.text, ( responseData ) => {

			if (responseData.ecode != 0)
			{
				NGUITools.SetActive(emptyListObject, true);
				return;
			}

			GameObject g = null;
			int idx = 0;

			RemoveAllFindFriend();

			if (responseData.data.Count <= 0)
			{
				NGUITools.SetActive(emptyListObject, true);
				return;
			}

			NGUITools.SetActive(emptyListObject, false);

			EPLog.Log ("---------------------");

			foreach (FriendModel fm in responseData.data)
			{
				g = NGUITools.AddChild(findFriendGrid.transform.gameObject, findFriendCell);
				g.transform.localScale = Vector3.one;
				g.name = FIND_FRIEND_CELL_NAME;
				
				FindFriendCell ffc = g.GetComponent<FindFriendCell>();
				ffc.indexPath = idx;

				ffc.nameLabel.text = fm.name;
				ffc.levelLabel.text = string.Format("Lv {0}", fm.lv.ToString());
				ffc.lastAccessLabel.text = DatetimeToFomattedString(fm.lastAccess);

				findFriendObjectList.Add (idx, g);
				findFriendList.Add (idx, fm);

				NGUITools.SetActive(g, true);

				idx++;
			}
			findFriendGrid.Reposition();
		});
	}
	*/

	public void RequestFriendProcess(int selectedIndexPath)
	{
		NetworkManager.Instance.C2S_FRIEND_SEND_REQ(findFriendList[selectedIndexPath].id, (responseData) => {
			if (responseData.ecode != 0)
			{
				PopupUtility.OneButtonErrorPopupNoBackground(responseData.ecode);
				return;
			}

			PopupUtility.OneButtonErrorPopupNoBackground(Localization.Get("uiFriendrequestFriend"));

			if (sceneObject.GetComponent<FriendScene>() != null)
			{
				FriendScene fs = sceneObject.GetComponent<FriendScene>();
				if (fs.currentTab == FriendScene.TAB_TYPE.DEAULT_FRIEND)
					fs.LoadDefaultFriend(true);
				else
					fs.LoadRequestFriend(true);
			}
		});
	}

	public string DatetimeToFomattedString(long dateGap)
	{
		DateTime nowDate = DateTime.Now;
		
		DateTime startDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
		DateTime targetDate = startDate.AddMilliseconds(dateGap).ToLocalTime();
		
		TimeSpan ts = nowDate - targetDate;
		
		if (ts.Days >= 60)
		{
			return Localization.Get("uiFriendTimeTypeD");
		}
		else if (ts.Days >= 1)
		{
			return string.Format(Localization.Get("uiFriendTimeTypeA"), ts.Days.ToString());
			//return string.Format("[AAAAFF]" + Localization.Get("uiFriendTimeTypeA"), ts.Days.ToString());
		}
		else if (ts.Hours > 0)
		{
			return string.Format(Localization.Get("uiFriendTimeTypeB"), ts.Hours.ToString(), ts.Minutes.ToString());
			//return string.Format("[AAAAFF]" + Localization.Get("uiFriendTimeTypeB"), ts.Hours.ToString(), ts.Minutes.ToString());
		}
		else
		{
			return string.Format(Localization.Get("uiFriendTimeTypeC"), ts.Minutes.ToString());
			//return string.Format("[AAAAFF]" + Localization.Get("uiFriendTimeTypeC"), ts.Minutes.ToString());
		}
	}
}
